package org.example.lease.service.dutyhandler.loginduty.impl;

import org.example.common.exception.LeaseException;
import org.example.lease.model.result.ResultCodeEnum;
import org.example.lease.service.dutyhandler.loginduty.AbstractLoginHandler;
import org.example.lease.vo.login.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 验证码验证处理器
 */
@Component
public class CaptchaValidateHandler extends AbstractLoginHandler {
    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public CaptchaValidateHandler(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 验证码验证逻辑处理器
     *
     * @param loginVo 登录信息
     * @return null
     */
    @Override
    protected String doHandle(LoginVo loginVo) {
        String captchaCode = loginVo.getCaptchaCode();
        if (!StringUtils.hasText(captchaCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        String captchaCodeFromRedis = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (captchaCodeFromRedis == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!captchaCodeFromRedis.equals(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        return null;
    }
}